package com.fyx.timedTask;

import com.alibaba.fastjson.JSONObject;
import com.fyx.config.*;
import com.fyx.entity.*;
import com.fyx.mapper.ChannelDataMapper;
import com.fyx.until.DateUtil;
import com.fyx.until.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Component(value="PeakRecordTask")
public class PeakRecordTask {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = FourthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fourthMongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;

    @Resource(name = NinethMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate ninethMongoTemplate;

    public void run(){
        record();
        channelDate();
        log.info("峰值分析任务：执行完毕=======================");
    }

    private void record(){
       long beginTime = new Date().getTime()/1000-3600;
       long endTime = new Date().getTime()/1000;

        //用户在线人数记录
        ActiveUserEntity activeUserEntity = new ActiveUserEntity();
        activeUserEntity.setTime(new Date().getTime()/1000);
        activeUserEntity.setQuantum(DateUtil.timeStamp2Date(String.valueOf(activeUserEntity.getTime()-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(activeUserEntity.getTime()),"HH:mm"));
        activeUserEntity.setChannel("total");
        JSONObject jsonObject = new JSONObject();

        JSONObject map = new JSONObject();
        map.put("cmd","online_count");
        map.put("args",jsonObject);

        String result = null,res=null,res2=null;
        try {
            result = HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(),"utf-8");
            res =  HttpUtil.post(RequestConfig.baseRequestUrl2, map.toJSONString(),"utf-8");
            res2 =  HttpUtil.post(RequestConfig.baseRequestUrl1, map.toJSONString(),"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(result)){
            log.info("获取在线人数请求失败");
            activeUserEntity.setNum(0);
        }else {
            jsonObject = JSONObject.parseObject(result);
            activeUserEntity.setNum(jsonObject.getIntValue("onlineNum"));
        }
        fourthMongoTemplate.insert(activeUserEntity);
        activeUserEntity.setChannel("totalcl");
        activeUserEntity.setId(null);
        if (StringUtils.isBlank(res)){
            log.info("获取在线人数请求失败");
            activeUserEntity.setNum(0);
        }else {
            jsonObject = JSONObject.parseObject(res);
            activeUserEntity.setNum(jsonObject.getIntValue("onlineNum"));
        }
        fourthMongoTemplate.insert(activeUserEntity);
        activeUserEntity.setChannel("totalapp");
        activeUserEntity.setId(null);
        if (StringUtils.isBlank(res2)){
            log.info("获取在线人数请求失败");
            activeUserEntity.setNum(0);
        }else {
            jsonObject = JSONObject.parseObject(res2);
            activeUserEntity.setNum(jsonObject.getIntValue("onlineNum"));
        }
        fourthMongoTemplate.insert(activeUserEntity);

        //充值记录
        PayUserEntity payUserEntity = new PayUserEntity();
        PayUserEntity payUserEntity1=new PayUserEntity();
        PayUserEntity payUserEntity2=new PayUserEntity();
        payUserEntity.setTime(activeUserEntity.getTime());
        payUserEntity.setQuantum(activeUserEntity.getQuantum());
        payUserEntity.setChannel("total");
        payUserEntity1.setTime(activeUserEntity.getTime());
        payUserEntity1.setQuantum(activeUserEntity.getQuantum());
        payUserEntity1.setChannel("totalcl");
        payUserEntity2.setTime(activeUserEntity.getTime());
        payUserEntity2.setQuantum(activeUserEntity.getQuantum());
        payUserEntity2.setChannel("totalapp");
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("time_end").gte(beginTime).lte(endTime));
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("total_fee").as("totalFee")
        );
        AggregationResults<OrderEntity> ar = mongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        AggregationResults<OrderEntity> ar1 = fiveMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        AggregationResults<OrderEntity> ar2 = ninethMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        List<OrderEntity> list = ar.getMappedResults();
        List<OrderEntity> list1 = ar1.getMappedResults();
        List<OrderEntity> list2 = ar2.getMappedResults();
        double totalFee = 0;
        if (list.size()>0){
            totalFee = list.get(0).getTotalFee();
        }
        payUserEntity.setAmount(totalFee);
        totalFee = 0;
        if(list1.size()>0){
            totalFee= list1.get(0).getTotalFee();
        }
        payUserEntity1.setAmount(totalFee);
        totalFee = 0;
        if(list2.size()>0){
            totalFee= list1.get(0).getTotalFee();
        }
        payUserEntity2.setAmount(totalFee);
        //苹果支付
        criteria = new Criteria();
        criteria.andOperator(
                Criteria.where("time_end").gte(beginTime).lte(endTime)
                ,Criteria.where("platform").is("applepay")
        );
        aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("total_fee").as("totalFee")
        );
        ar = mongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        ar1= fiveMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        ar2= ninethMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        list = ar.getMappedResults();
        list1 =ar1.getMappedResults();
        list2 =ar2.getMappedResults();
        totalFee = 0;
        if (list.size()>0){
            totalFee =  list.get(0).getTotalFee();
        }
        payUserEntity.setAppleAmount(totalFee);
        totalFee = 0;
        if(list1.size()>0){
            totalFee= list1.get(0).getTotalFee();
        }
        payUserEntity1.setAppleAmount(totalFee);
        totalFee = 0;
        if(list2.size()>0){
            totalFee= list2.get(0).getTotalFee();
        }
        payUserEntity2.setAppleAmount(totalFee);
        //安卓支付
        criteria = new Criteria();
        criteria.andOperator(
                Criteria.where("time_end").gte(beginTime).lte(endTime)
                ,Criteria.where("platform").ne("applepay")
        );
        aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                Aggregation.group().sum("total_fee").as("totalFee"));
        ar = mongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        ar1= fiveMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        ar2= ninethMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        list = ar.getMappedResults();
        list1 =ar1.getMappedResults();
        list2 =ar2.getMappedResults();
        totalFee = 0;
        if (list.size()>0){
            totalFee = list.get(0).getTotalFee();
        }
        payUserEntity.setAndroidAmount(totalFee);
        totalFee = 0;
        if(list1.size()>0){
            totalFee= list1.get(0).getTotalFee();
        }
        payUserEntity1.setAndroidAmount(totalFee);
        totalFee = 0;
        if(list2.size()>0){
            totalFee= list2.get(0).getTotalFee();
        }
        payUserEntity2.setAndroidAmount(totalFee);
        fourthMongoTemplate.insert(payUserEntity);
        fourthMongoTemplate.insert(payUserEntity1);
        fourthMongoTemplate.insert(payUserEntity2);
        //活跃用户
        OnlineUserPeakEntity onlineUserPeakEntity = new OnlineUserPeakEntity();
        OnlineUserPeakEntity onlineUserPeakEntity1 = new OnlineUserPeakEntity();
        OnlineUserPeakEntity onlineUserPeakEntity2 = new OnlineUserPeakEntity();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        long dayBeginTime =Integer.valueOf(DateUtil.date2TimeStamp(ft.format(DateUtil.getDayBegin()),"yyyy-MM-dd HH:mm:ss"));
        onlineUserPeakEntity.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(activeUserEntity.getTime()),"HH:mm"));
        onlineUserPeakEntity.setTime(activeUserEntity.getTime());
        onlineUserPeakEntity.setChannel("total");
        onlineUserPeakEntity1.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(activeUserEntity.getTime()),"HH:mm"));
        onlineUserPeakEntity1.setTime(activeUserEntity.getTime());
        onlineUserPeakEntity1.setChannel("totalcl");
        onlineUserPeakEntity1.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(activeUserEntity.getTime()),"HH:mm"));
        onlineUserPeakEntity1.setTime(activeUserEntity.getTime());
        onlineUserPeakEntity1.setChannel("totalapp");
        long total = mongoTemplate.count(new Query(Criteria.where("last_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
        onlineUserPeakEntity.setNum((int) total);
        total = fiveMongoTemplate.count(new Query(Criteria.where("last_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
        onlineUserPeakEntity1.setNum((int) total);
        total = ninethMongoTemplate.count(new Query(Criteria.where("last_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
        onlineUserPeakEntity2.setNum((int) total);
        fourthMongoTemplate.insert(onlineUserPeakEntity);
        fourthMongoTemplate.insert(onlineUserPeakEntity1);
        fourthMongoTemplate.insert(onlineUserPeakEntity2);
        //注册用户
        AddUserPeakEntity addUserPeakEntity = new AddUserPeakEntity();
        AddUserPeakEntity addUserPeakEntity1 = new AddUserPeakEntity();
        AddUserPeakEntity addUserPeakEntity2 = new AddUserPeakEntity();
        addUserPeakEntity.setChannel("total");
        addUserPeakEntity1.setChannel("totalcl");
        addUserPeakEntity2.setChannel("totalapp");
        String str = DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm");
        if(str.equals("00:00")){
            addUserPeakEntity.setTime(endTime-60);
            addUserPeakEntity.setQuantum("00:00 - 24:00");
            addUserPeakEntity1.setTime(endTime-60);
            addUserPeakEntity1.setQuantum("00:00 - 24:00");
            addUserPeakEntity2.setTime(endTime-60);
            addUserPeakEntity2.setQuantum("00:00 - 24:00");
            long total1 = mongoTemplate.count(new Query(Criteria.where("reg_time").gte(endTime-24*3600).lte(endTime)), UserEntity.class);
            addUserPeakEntity.setNum((int) total1);
            total1 = fiveMongoTemplate.count(new Query(Criteria.where("reg_time").gte(endTime-24*3600).lte(endTime)), UserEntity.class);
            addUserPeakEntity1.setNum((int) total1);
            total1 = ninethMongoTemplate.count(new Query(Criteria.where("reg_time").gte(endTime-24*3600).lte(endTime)), UserEntity.class);
            addUserPeakEntity2.setNum((int) total1);
        }else{
            addUserPeakEntity.setTime(endTime);
            addUserPeakEntity.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
            addUserPeakEntity1.setTime(endTime);
            addUserPeakEntity1.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
            addUserPeakEntity2.setTime(endTime);
            addUserPeakEntity2.setQuantum("00:00 - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
            long total1 = mongoTemplate.count(new Query(Criteria.where("reg_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
            addUserPeakEntity.setNum((int) total1);
            total1 = fiveMongoTemplate.count(new Query(Criteria.where("reg_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
            addUserPeakEntity1.setNum((int) total1);
            total1 = ninethMongoTemplate.count(new Query(Criteria.where("reg_time").gte(dayBeginTime).lte(endTime)), UserEntity.class);
            addUserPeakEntity2.setNum((int) total1);
        }
        fourthMongoTemplate.insert(addUserPeakEntity);
        fourthMongoTemplate.insert(addUserPeakEntity1);

        //充值人数峰值
        RechargeUserPeakEntity rechargeUserPeakEntity = new RechargeUserPeakEntity();
        RechargeUserPeakEntity rechargeUserPeakEntity1 = new RechargeUserPeakEntity();
        RechargeUserPeakEntity rechargeUserPeakEntity2 = new RechargeUserPeakEntity();
        rechargeUserPeakEntity.setTime(endTime);
        rechargeUserPeakEntity.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeUserPeakEntity.setChannel("total");
        rechargeUserPeakEntity1.setTime(endTime);
        rechargeUserPeakEntity1.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeUserPeakEntity1.setChannel("totalcl");
        rechargeUserPeakEntity2.setTime(endTime);
        rechargeUserPeakEntity2.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeUserPeakEntity2.setChannel("totalapp");
        criteria = new Criteria();
        criteria.andOperator(Criteria.where("time_end").gte(endTime-3600).lte(endTime));
        aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("pid")
        );
         ar = mongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
         ar1 = fiveMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
        ar2 = ninethMongoTemplate.aggregate(aggregation, "order", OrderEntity.class);
         list = ar.getMappedResults();
         list1 = ar1.getMappedResults();
        list2 = ar2.getMappedResults();
        rechargeUserPeakEntity.setNum(list.size());
        rechargeUserPeakEntity1.setNum(list1.size());
        rechargeUserPeakEntity2.setNum(list2.size());
        fourthMongoTemplate.insert(rechargeUserPeakEntity);
        fourthMongoTemplate.insert(rechargeUserPeakEntity1);
        fourthMongoTemplate.insert(rechargeUserPeakEntity2);

        //充值次数峰值
        RechargeCountPeakEntity rechargeCountPeakEntity = new RechargeCountPeakEntity();
        RechargeCountPeakEntity rechargeCountPeakEntity1 = new RechargeCountPeakEntity();
        RechargeCountPeakEntity rechargeCountPeakEntity2 = new RechargeCountPeakEntity();
        rechargeCountPeakEntity.setTime(endTime);
        rechargeCountPeakEntity.setChannel("total");
        rechargeCountPeakEntity.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeCountPeakEntity1.setTime(endTime);
        rechargeCountPeakEntity1.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeCountPeakEntity1.setChannel("totalcl");
        rechargeCountPeakEntity2.setTime(endTime);
        rechargeCountPeakEntity2.setQuantum(DateUtil.timeStamp2Date(String.valueOf(endTime-3600),"HH:mm") +" - " + DateUtil.timeStamp2Date(String.valueOf(endTime),"HH:mm"));
        rechargeCountPeakEntity2.setChannel("totalapp");
        long total2 = mongoTemplate.count(new Query(Criteria.where("time_end").gte(endTime-3600).lte(endTime)), OrderEntity.class);
        rechargeCountPeakEntity.setNum((int) total2);
        total2 = fiveMongoTemplate.count(new Query(Criteria.where("time_end").gte(endTime-3600).lte(endTime)), OrderEntity.class);
        rechargeCountPeakEntity1.setNum((int) total2);
        total2 =ninethMongoTemplate.count(new Query(Criteria.where("time_end").gte(endTime-3600).lte(endTime)), OrderEntity.class);
        rechargeCountPeakEntity2.setNum((int) total2);
        fourthMongoTemplate.insert(rechargeCountPeakEntity);
        fourthMongoTemplate.insert(rechargeCountPeakEntity1);
        fourthMongoTemplate.insert(rechargeCountPeakEntity2);
    }

    @Autowired
    private ChannelDataMapper channelDataMapper;
    private void channelDate(){
        Long time=new Date().getTime()/1000;
        Long beginTime=DateUtil.getDayBegin().getTime()/1000;
        ChannelData channelData=new ChannelData();
        channelData.setTime(time.intValue());
        Query query=new Query();
        Criteria criteria=new Criteria();
        criteria.and("day").is(beginTime);
        query.addCriteria(criteria);
        List<ChannelDataEntity>  list= mongoTemplate.find(query,ChannelDataEntity.class);
        if(list.size()>0){
            for (ChannelDataEntity channelDataEntity:list){
                channelData.setChannel(channelDataEntity.getChannel());
                channelData.setDay(channelDataEntity.getDay());
                channelData.setActNum(channelDataEntity.getAct_num());
                channelData.setChargeAmount(channelDataEntity.getCharge_amount());
                channelData.setChargePnum(channelDataEntity.getCharge_pnum());
                channelData.setFirstChargePnum(channelDataEntity.getFirst_charge_pnum());
                channelData.setNewChargeAmount(channelDataEntity.getNew_charge_amount());
                channelData.setNewChargePnum(channelDataEntity.getNew_charge_pnum());
                channelData.setPlayedUserCount(channelDataEntity.getPlayed_user_count());
                channelData.setPlayedNewUserCount(channelDataEntity.getPlayed_new_user_count());
                channelData.setRegNum(channelDataEntity.getReg_num());
                String str="";
                for(int i=0;i<channelDataEntity.getRetention().length;i++){
                    if(i==(channelDataEntity.getRetention().length-1)){
                        str+=channelDataEntity.getRetention()[i]+"";
                    }
                    else {
                    str+=channelDataEntity.getRetention()[i]+",";}
                }
                channelData.setRetentions(str);
                channelData.setTotalCharge(channelDataEntity.getTotal_charge());
                channelDataMapper.insert(channelData);
            }
        }
    }
}
